package rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class ProducerDemo {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("101.42.168.168");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");// 用户名
        connectionFactory.setPassword("admin"); // 密码
        connectionFactory.setVirtualHost("guan");//虚拟主机
        Connection connection = connectionFactory.newConnection();
        //2. 开启通道
        Channel channel = connection.createChannel();
        //3.声明交换机 使用内置的交换机

        //4.声明队列
        /*
        * public com.rabbitmq.client.impl.AMQImpl.Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive,
        *                                                                            boolean autoDelete, Map<String, Object> arguments)
        * 参数说明
        * queue: 队列名称
        * durable: 是否持久化.true-设置队列为持久化, 待久化的队列会存盘,服务器重启之后, 消息不丢失。
        * exclusive
        *               * 是否独占, 只能有⼀个消费者监听队列
        *               * 当Connection关闭时, 是否删除队列
        * autoDelete: 是否⾃动删除, 当没有Consumer时, ⾃动删除掉
        * arguments: ⼀些参数
        *
        * */
        channel.queueDeclare("queue1", true, false, false, null);
        //5.发送消息
        /*
        * void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
        *
        * 参数说明
        *
        * exchange：交换机名称
        * routingKey：内置交换机，routingKey和队列名称保持一致
        * props：属性配置
        * body：消息
         * */
        for (int i = 0; i < 10; i++) {
            String msg = "hello rabbitMQ"+ i;
            channel.basicPublish("","queue1",null,msg.getBytes(StandardCharsets.UTF_8));
        }

        //打印方便观察
        System.out.println("消息发送成功！即将关闭连接~");

        //6.资源释放
        //channel.close();
        //connection.close();
    }
}
